import React from 'react';
import { connect } from 'dva';
// import styles from './BasicLayout.less';
import DocumentTitle from 'react-document-title';
import { Layout } from 'antd';
import Header from './Header';
import Footer from './Footer';
import SiderMenu from './SiderMenu';
import Content from './Content';
import { title } from '../defaultSettings';
import PageLoading from '@/components/PageLoading';

class BasicLayout extends React.Component {

  componentDidMount() {
    const {
      dispatch,
      route: { routes, path },
      authority,
    } = this.props;
    dispatch({
      type: 'login/getByToken',
      payload: { routes, path, authority },
    });
  }

  state = {
    collapsed: false,
  };

  getLayoutStyle = () => {
    return {
      paddingLeft: this.state.collapsed ? '80px' : '200px',
    };
  };

  handleMenuCollapse = collapsed => {
    this.setState({
      collapsed,
    });
  };

  getPageTitle = (pathname, breadcrumbNameMap) => {
    let pageTitle = '';
    try {
      breadcrumbNameMap.forEach(item => {
        if (pathname === item.path) {
          pageTitle = item.name + ' - ' + title;
          throw new Error('EndIterative');
        }
      });
    } catch { }
    return pageTitle;
  };

  render() {
    const { location, breadcrumbNameMap, loading } = this.props;
    return (loading.effects['login/getByToken']) ?
      (<PageLoading />) :
      (<DocumentTitle title={this.getPageTitle(location.pathname, breadcrumbNameMap)}>
        <Layout style={{ minHeight: '100vh' }}>
          <SiderMenu collapsed={this.state.collapsed} {...this.props}></SiderMenu>
          <Layout
            style={{
              ...this.getLayoutStyle(),
              minHeight: '100vh',
            }}>
            <Header collapsed={this.state.collapsed} onCollapse={this.handleMenuCollapse}  {...this.props}></Header>
            <Content {...this.props}></Content>
            <Footer></Footer>
          </Layout>
        </Layout>
      </DocumentTitle>);
  }
}

export default connect(({ menu: menuModel, login: loginModel, loading }) => ({
  menuData: menuModel.menuData,
  breadcrumbNameMap: menuModel.breadcrumbNameMap,
  currentUser: loginModel.currentUser,
  authority: loginModel.authority,
  loading,
}))(props => (
  <BasicLayout {...props} />
));
